using System;
using System.Web;
using System.Web.Caching;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;

namespace webapp4U
{
    /// <summary>
    /// Public class to load all language XML files into cache for quick access.
    /// </summary>
    public class ResourceManager 
    {

        public static string GetString(string name) 
        {
            try
            {
                // chi bat len khi chay thu nghiem
                HttpContext.Current.Cache.Remove("strLanguages");

                Hashtable resources = GetResource();

                if (resources[name] == null)
                {
                    // LN 6/9/04: Changed to throw a forums exception 
                    return "[" + name.ToString() + "]";
                    //HttpContext.Current.Response("Loi roi",true);
                }

                return (string)resources[name];
            }
            catch
            {
                return name;
            }
        }

        private static Hashtable GetResource()
        {
            Hashtable resources;

            string cacheKey = "strLanguages";

            if (HttpContext.Current.Cache[cacheKey]==null)
            {
                resources = new Hashtable();
                LoadResource(resources,cacheKey);
            }

            return (Hashtable)HttpContext.Current.Cache[cacheKey];
        }


		private static void LoadResource(Hashtable target,string cacheKey) 
        {
			//string filePath = forumContext.Context.Server.MapPath("~" + ForumConfiguration.GetConfig().ForumFilesPath + "/Languages/" + language + "/{0}");

            string filePath;
            if (Globals.LangVietNam())
                filePath = HttpContext.Current.Request.PhysicalApplicationPath + "//Languages//Languages.xml";
            else
                filePath = HttpContext.Current.Request.PhysicalApplicationPath + "//Languages//Languages_en.xml";
            
			CacheDependency dp = new CacheDependency(filePath);

			XmlDocument d = new XmlDocument();
            try
            {
                d.Load(filePath);
            }
            catch
            {
                return;
            }

			foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes) 
            {
				if (n.NodeType != XmlNodeType.Comment) // bo qua phan ghi chu cua xml
                {
					if (target[n.Attributes["name"].Value] == null)
						target.Add(n.Attributes["name"].Value, n.InnerText);
					else
						target[n.Attributes["name"].Value] = n.InnerText;
				}
			}
            
            HttpContext.Current.Cache.Insert(cacheKey, target);

        }


    }
}
